#!/usr/bin/python3.2
import re
import Math
import System
import os
import subprocess
import threading
import Server
import builtins
from random import choice
import Database as db
import Contact
import datetime

actions=[]
simples=[]
pronoms=[]
history=[]
error=""
fct=""
var=""

def init():
    global dico
    dico=[]
    dic=open("dico/dico-fr.txt","r")
    for line in dic:
        dico.append(line.strip())    

def chercheType(receive):
        typeP="affirmation"
        if receive[-1:] == "!":
                typeP="exclamation"
        elif receive[-1:] == "?":
                typeP="interrogation"
        elif receive[-3:] == "...":
                typeP="suspension"
        elif (re.search("ne",receive) or re.search("n",receive)) and (re.search("pas",receive) or re.search("plus",receive) or re.search("jamais",receive)):
                typeP="negation"
        else:
                typeP="affirmation"
        return typeP

def compareMot(mot2):
    res = 'nn'
    perc=''
    m=''
    lres=[]
    lperc=[]
    lperc2=[]
    for mot in dico:
        if mot == mot2:
            res='id'
            m=mot
            perc=100
            break
        else:
            if len(mot) >= len(mot2): 
                i=len(mot)
                k=len(mot2)
            else:
                i=len(mot2)
                k=len(mot)
            j=0
            for l in range(k):
                if mot[l]==mot2[l]:
                    j=j+1
            if i != 0:
                perc=100-((i-j)/i*100)
                lres.append(mot)
                lperc.append(perc)
                lperc2.append(perc)
            lperc2.sort()
            perc=lperc2[len(lperc2)-1]
            index=lperc.index(perc)
            m=lres[index]
            res='re'
    return res,m,perc

def lanceCommande(commande,typeAction):
        if typeAction=="bash":
#            print(commande)
            res=System.command(commande)                
        elif typeAction=="python" or typeAction=="intern":
            res=eval(commande)
#            print(res)
        return res

def analyse(receive,username):
#error,quest,nom fct
        global history
        global error
        global fct
        global var
        reponse=""
        type=""
        typ="T"
        if error != "":
            if error == "manqueSujet":
                t=history[len(history)-1].split(";")
                t2=t[0].split(" ")
                var1=t2[4]
                var="'"+var1+"',\""+receive+"\""
            else:
                var=var+",\""+receive+"\""
            cmd=str(fct)+"("+str(var)+")"
            res=lanceCommande(cmd,"intern")
            if len(res) > 0:
                error=res[0]
                quest=res[1]
                fct=res[2]
                reponse=quest
                typ="Q"
        elif len(history) > 0 and re.match(receive,history[len(history)-1]):
            reponse="Je vous ai déjà répondu"
            typ="T"
            type="repondu"
        else:
            logFile=open("logs","a")
            typeP=chercheType(receive)
            phraseM=receive.replace("'"," ")
            listeMot=phraseM.split(" ")
#            listeMot2=[]
#            for mot in listeMot:
#                result,mot2,perc=compareMot(mot)
#                listeMot2.append(mot2)
#            receiveCorrected=" ".join(listeMot2)
#            print("rc="+str(receiveCorrected))
            if (re.search("[calcul|combien|pythagore|thales|perimetre|surface|volume|triangle]?[-+]?\d+",receive) and typeP=="interrogation") or re.search("([-+]?\d+)+",receive):
                if re.search("[triangle,rectangle]",receive):
                    receive+=" pythagore"
                reponse=Math.run(receive)
                typ="T"
            else:
                type,reponse=db.chercherPhrase(receive)
                if type == "action":
                    typeAction,commande,rep=db.chercherAction(receive)
                    if commande != "":
                        t=commande.split(" ")
                        for i in range(len(t)):
                            if t[i]=="%IN%":
                                t[i]=listeMot[4]
                        if re.search("%IN%",commande):
                            cmd = "'".join(t)
                        else:
                            cmd = commande
                        if re.search("%OUT%",rep) and typeAction=="bash":
                            res=subprocess.check_output(commande,shell=True)
                            logFile.write(commande+";"+datetime.datetime.now().isoformat()+";"+username+"\n")
                            res=res.decode()
                        elif re.search("%OUT%",rep) and typeAction=="intern":
                            res=lanceCommande(cmd,typeAction)
                            logFile.write(commande+";"+datetime.datetime.now().isoformat()+";"++username+"\n")
                        else:
                            res=lanceCommande(cmd,typeAction)
                            logFile.write(cmd+";"+datetime.datetime.now().isoformat()+";"+username+"\n")
                    if isinstance(res, str):
                        t=rep.split(" ")
                        for i in range(len(t)):
                            if t[i]=="%OUT%":
                                try:
                                    t[i]=res.decode().strip()
                                except:
                                    t[i]=res.strip()
                        reponse = " ".join(t)
                        typ="T"
                    else:
                        error=res[0]
                        quest=res[1]
                        fct=res[2]
                        reponse=quest
                        typ="T"
        history.append(str(receive)+";"+str(reponse)+";"+str(type))    
        return typ,str(reponse)

def cleanHistory():
    global history
    history=[]
